// 个人空间页面逻辑
// 假设已登录，用户信息存在localStorage/sessionStorage

document.addEventListener('DOMContentLoaded', function() {
  // 用户信息加载
  const avatar = document.getElementById('profileAvatar');
  const nickname = document.getElementById('profileNickname');
  const userId = document.getElementById('profileId');
  const username = document.getElementById('profileUsername');
  const emailDiv = document.getElementById('profileEmail');
  // 假设本地存储有这些信息
  const user = {
    avatar: localStorage.getItem('avatar') || sessionStorage.getItem('avatar') || 'img/avatar.png',
    nickname: localStorage.getItem('nickname') || sessionStorage.getItem('nickname') || sessionStorage.getItem('username') || '未登录',
    id: localStorage.getItem('userId') || sessionStorage.getItem('userId') || '未知',
    username: localStorage.getItem('username') || sessionStorage.getItem('username') || 'unknown',
    email: localStorage.getItem('email') || sessionStorage.getItem('email') || ''
  };
  avatar.src = user.avatar;
  nickname.textContent = user.nickname;
  userId.textContent = '通行ID: ' + user.id;
  username.textContent = '@' + user.username;
  emailDiv.textContent = user.email ? '邮箱: ' + user.email : '';

  // 编辑邮箱弹窗逻辑
  const editEmailModal = document.getElementById('editEmailModal');
  const editEmailBtn = document.getElementById('profileEditBtn');
  const editEmailForm = document.getElementById('editEmailForm');
  const newEmailInput = document.getElementById('newEmailInput');
  const cancelEditEmail = document.getElementById('cancelEditEmail');

  editEmailBtn.onclick = function() {
    newEmailInput.value = user.email || '';
    editEmailModal.style.display = 'flex';
  };
  cancelEditEmail.onclick = function() {
    editEmailModal.style.display = 'none';
  };
  editEmailForm.onsubmit = function(e) {
    e.preventDefault();
    const newEmail = newEmailInput.value.trim();
    if (!newEmail) {
      showCenterModal('请输入新邮箱');
      return;
    }
    // 简单邮箱格式校验
    if (!/^\S+@\S+\.\S+$/.test(newEmail)) {
      showCenterModal('邮箱格式不正确');
      return;
    }
    // 请求后端更新
    fetch('http://localhost:3000/api/users/update', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': sessionStorage.getItem('token') || ''
      },
      body: JSON.stringify({
        username: user.username,
        email: newEmail,
        role: localStorage.getItem('role') || sessionStorage.getItem('role') || 'registered'
      })
    })
    .then(res => res.json())
    .then(data => {
      if (data.message) {
        // 更新本地存储
        localStorage.setItem('email', newEmail);
        sessionStorage.setItem('email', newEmail);
        emailDiv.textContent = '邮箱: ' + newEmail;
        editEmailModal.style.display = 'none';
        showCenterModal('邮箱修改成功！');
      } else {
        showCenterModal(data.error || '邮箱修改失败');
      }
    })
    .catch(() => {
      showCenterModal('邮箱修改失败');
    });
  };

  // 菜单切换
  const menuAdd = document.getElementById('menuAdd');
  const menuSuggestion = document.getElementById('menuSuggestion');
  const sectionAdd = document.getElementById('sectionAdd');
  const sectionSuggestion = document.getElementById('sectionSuggestion');
  menuAdd.onclick = function() {
    menuAdd.classList.add('active');
    menuSuggestion.classList.remove('active');
    sectionAdd.style.display = '';
    sectionSuggestion.style.display = 'none';
  };
  menuSuggestion.onclick = function() {
    menuSuggestion.classList.add('active');
    menuAdd.classList.remove('active');
    sectionAdd.style.display = 'none';
    sectionSuggestion.style.display = '';
    loadMySuggestions();
  };

  // 我的添加：三表切换
  const addTableTabs = document.querySelectorAll('.add-table-tab');
  addTableTabs.forEach(tab => {
    tab.onclick = function() {
      addTableTabs.forEach(t => t.classList.remove('active'));
      this.classList.add('active');
      loadMyAddTable(this.dataset.table);
    };
  });
  // 默认加载食物表
  loadMyAddTable('foods');

  // 加载当前用户添加的表数据 - 进一步优化版本
  function loadMyAddTable(table) {
    const listDiv = document.getElementById('addTableList');
    
    // 获取或创建加载状态元素
    let loadingDiv = listDiv.querySelector('.table-loading');
    if (!loadingDiv) {
      loadingDiv = document.createElement('div');
      loadingDiv.className = 'table-loading';
      loadingDiv.textContent = '加载中...';
      listDiv.appendChild(loadingDiv);
    }
    loadingDiv.style.display = 'block';
    
    // 隐藏之前的表格内容，但不删除
    const existingTable = listDiv.querySelector('.table-container');
    const existingEmpty = listDiv.querySelector('.table-empty');
    if (existingTable) {
      existingTable.style.opacity = '0';
      setTimeout(() => {
        existingTable.style.display = 'none';
      }, 300);
    }
    if (existingEmpty) {
      existingEmpty.style.opacity = '0';
      setTimeout(() => {
        existingEmpty.style.display = 'none';
      }, 300);
    }
    
    // 用用户ID过滤
    const userId = localStorage.getItem('userId') || sessionStorage.getItem('userId') || '';
    fetch(`http://localhost:3000/api/${table}?created_by=${encodeURIComponent(userId)}`, {
      headers: { 'Authorization': sessionStorage.getItem('token') || '' }
    })
    .then(res => res.json())
    .then(data => {
      // 隐藏加载状态
      loadingDiv.style.display = 'none';
      
      // 移除旧的表格和空数据元素
      const oldTable = listDiv.querySelector('.table-container');
      const oldEmpty = listDiv.querySelector('.table-empty');
      if (oldTable) oldTable.remove();
      if (oldEmpty) oldEmpty.remove();
      
      if (!Array.isArray(data) || data.length === 0) {
        // 创建空数据状态元素
        const emptyDiv = document.createElement('div');
        emptyDiv.className = 'table-empty';
        emptyDiv.textContent = '暂无数据';
        emptyDiv.style.opacity = '0';
        listDiv.appendChild(emptyDiv);
        
        // 淡入效果
        setTimeout(() => {
          emptyDiv.style.opacity = '1';
        }, 50);
        return;
      }
      
      // 构建表格HTML
      let html = '<table><thead><tr>';
      // 只显示部分字段
      const fields = {
        foods: ['name','origin','production_date','producer','season'],
        ingredients: ['name','category','origin','production_date','producer','price','supplier'],
        products: ['name','origin','production_date','producer','price','supplier']
      }[table] || Object.keys(data[0]);
      html += fields.map(f => `<th>${getFieldLabel(f)}</th>`).join('') + '</tr></thead><tbody>';
      data.forEach(row => {
        html += '<tr>' + fields.map(f => `<td>${row[f] !== undefined ? row[f] : ''}</td>`).join('') + '</tr>';
      });
      html += '</tbody></table>';
      
      // 创建新的表格容器
      const tableContainer = document.createElement('div');
      tableContainer.className = 'table-container';
      tableContainer.innerHTML = html;
      tableContainer.style.opacity = '0';
      listDiv.appendChild(tableContainer);
      
      // 淡入效果
      setTimeout(() => {
        tableContainer.style.opacity = '1';
      }, 50);
    })
    .catch(() => {
      // 隐藏加载状态
      loadingDiv.style.display = 'none';
      
      // 移除旧的表格和空数据元素
      const oldTable = listDiv.querySelector('.table-container');
      const oldEmpty = listDiv.querySelector('.table-empty');
      if (oldTable) oldTable.remove();
      if (oldEmpty) oldEmpty.remove();
      
      // 创建错误状态元素
      const errorDiv = document.createElement('div');
      errorDiv.className = 'table-empty';
      errorDiv.textContent = '加载失败';
      errorDiv.style.opacity = '0';
      listDiv.appendChild(errorDiv);
      
      // 淡入效果
      setTimeout(() => {
        errorDiv.style.opacity = '1';
      }, 50);
    });
  }

  // 我的建议：按状态分组 - 优化版本
  function loadMySuggestions() {
    const listDiv = document.getElementById('mySuggestionList');
    listDiv.innerHTML = '<div style="color:#888;padding:24px;text-align:center;">加载中...</div>';
    const userId = localStorage.getItem('userId') || sessionStorage.getItem('userId') || '';
    fetch('http://localhost:3000/api/suggestions?user_id=' + encodeURIComponent(userId), {
      headers: { 'Authorization': sessionStorage.getItem('token') || '' }
    })
    .then(res => res.json())
    .then(data => {
      if (!Array.isArray(data) || data.length === 0) {
        listDiv.innerHTML = '<div style="color:#aaa;padding:24px;text-align:center;">暂无建议</div>';
        return;
      }
      // 按状态分组（用中文key）
      const group = { '待处理': [], '审核中': [], '已采纳': [], '已拒绝': [] };
      data.forEach(item => {
        group[item.status] && group[item.status].push(item);
      });
      let html = '';
      const statusMap = {
        '待处理': '待处理', '审核中': '审核中', '已采纳': '已采纳', '已拒绝': '已拒绝'
      };
      const badgeClass = {
        '待处理': 'suggestion-status-badge suggestion-status-pending',
        '审核中': 'suggestion-status-badge suggestion-status-reviewing',
        '已采纳': 'suggestion-status-badge suggestion-status-approved',
        '已拒绝': 'suggestion-status-badge suggestion-status-rejected'
      };
      Object.keys(group).forEach(status => {
        if (group[status].length > 0) {
          html += `<div class="suggestion-group">
            <div class="suggestion-group-title"><span class="${badgeClass[status]}">${statusMap[status]}</span></div>`;
          group[status].forEach(sug => {
            html += `<div class="suggestion-item">
              <div style="font-size:16px;font-weight:600;margin-bottom:6px;">${sug.title}</div>
              <div style="color:#666;margin-bottom:8px;">${sug.content}</div>
              <div style="font-size:13px;color:#888;">提交时间：${formatDate(sug.submit_time || sug.created_at)} | 投票：${sug.votes || 0}</div>
            </div>`;
          });
          html += '</div>';
        }
      });
      listDiv.innerHTML = html || '<div style="color:#aaa;padding:24px;text-align:center;">暂无建议</div>';
    })
    .catch(() => {
      listDiv.innerHTML = '<div style="color:#aaa;padding:24px;text-align:center;">加载失败</div>';
    });
  }

  function getFieldLabel(f) {
    return {
      name: '名称', origin: '产地', production_date: '出产日期', producer: '生产单位', season: '出产季节',
      category: '分类', price: '价格', supplier: '供货商'
    }[f] || f;
  }
  function formatDate(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    if (isNaN(date)) return dateString;
    return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', {hour: '2-digit', minute: '2-digit'});
  }

  // 编辑按钮（可扩展）
});

// 绿色主题弹窗
function showCenterModal(message, callback) {
  let modal = document.createElement('div');
  modal.style.position = 'fixed';
  modal.style.left = '0';
  modal.style.top = '0';
  modal.style.width = '100vw';
  modal.style.height = '100vh';
  modal.style.background = 'rgba(0,0,0,0.18)';
  modal.style.display = 'flex';
  modal.style.alignItems = 'center';
  modal.style.justifyContent = 'center';
  modal.style.zIndex = '9999';
  modal.innerHTML = `<div style="background:#fff;border-radius:12px;box-shadow:0 4px 24px #388e3c22;padding:32px 36px;min-width:320px;text-align:center;">
      <div style='font-size:20px;font-weight:600;margin-bottom:12px;color:#388e3c;'>提示</div>
      <div style='font-size:16px;margin-bottom:24px;'>${message}</div>
      <button id='centerModalBtn' style='background:#4caf50;color:#fff;border:none;border-radius:6px;padding:8px 32px;font-size:16px;cursor:pointer;'>确定</button>
  </div>`;
  document.body.appendChild(modal);
  document.getElementById('centerModalBtn').onclick = function() {
      document.body.removeChild(modal);
      if (callback) callback();
  };
} 